package com.yc.sole.system.repository;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.sole.system.dto.RoleMenuDto;
import com.yc.sole.system.entity.RoleMenu;
import com.yc.sole.system.mapper.RoleMenuMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 服务接口实现
 *
 * @author yizuomin
 * @date 2023-03-26
 **/
@Slf4j
@Service
public class RoleMenuRepository extends ServiceImpl<RoleMenuMapper, RoleMenu> {

    /**
     * 根据角色id删除角色菜单关联
     *
     * @param roleIds
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteRoleMenuByRoleId(Collection<Long> roleIds) {
        LambdaQueryWrapper<RoleMenu> wrapper = Wrappers.<RoleMenu>lambdaQuery().in(RoleMenu::getRoleId, roleIds);
        this.remove(wrapper);
    }

    /**
     * 根据菜单id删除角色菜单关联
     *
     * @param menuIds
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteByMenuIds(Collection<Long> menuIds) {
        LambdaQueryWrapper<RoleMenu> wrapper = Wrappers.<RoleMenu>lambdaQuery().in(RoleMenu::getMenuId, menuIds);
        this.remove(wrapper);
    }

    /**
     * 批量新增
     *
     * @param roleMenuDtos
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatchRoleMenu(List<RoleMenuDto> roleMenuDtos) {
        List<RoleMenu> roleMenuList = BeanUtil.copyToList(roleMenuDtos, RoleMenu.class);
        this.saveBatch(roleMenuList);
    }

    /**
     * 根据角色id查询
     *
     * @param roleId
     * @return
     */
    public List<RoleMenuDto> selectByRoleId(Long roleId) {
        LambdaQueryWrapper<RoleMenu> wrapper = Wrappers.<RoleMenu>lambdaQuery().eq(RoleMenu::getRoleId, roleId);
        return BeanUtil.copyToList(this.list(wrapper), RoleMenuDto.class);
    }

    /**
     * 根据角色id查询
     *
     * @param roleIds
     * @return
     */
    public Set<Long> selectMenuIdByRoleIds(Collection<Long> roleIds) {
        LambdaQueryWrapper<RoleMenu> roleMenuWrapper = Wrappers.<RoleMenu>lambdaQuery()
                .select(RoleMenu::getMenuId)
                .in(RoleMenu::getRoleId, roleIds);
        return this.list(roleMenuWrapper).stream().map(RoleMenu::getMenuId).collect(Collectors.toSet());
    }
}
